package com.example.controller;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.example.entity.User;
import com.example.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;
import java.util.List;

@Controller
public class UserController {

    @Autowired
    private UserService userService;

    @RequestMapping("/queryUser")
    @ResponseBody
    public List<User> queryUsers() {
        return userService.getAll();
    }

    @RequestMapping("/tologin")
    public String login(User user, HttpSession session, Model model){
        List<User> userinfoList=userService.getUserList(user);
        if(!CollectionUtils.isEmpty(userinfoList)){
            session.setAttribute("USER_INFO",userinfoList.get(0));
          return "forward:/"; //相当于回滚返回首页面

        }

        return "forward:/login"; //???
    }

    @RequestMapping("/login")
    public String toLogin(){
        return "edge/login";
    }


    @RequestMapping("/register-complete")
    public String register(User user){
        int i=userService.addUser(user);
        if(i>0){
            return "edge/register-complete"; //成功界面
        }
        return "forwad:/edge/register"; //失败界面
    }
    @RequestMapping("/register")
    public String toRegister(){
        return "edge/register";
    }

    /**
     * 退出登录
     */
    @RequestMapping( "/logout")
    public String logout(HttpSession session) {
        // 清除Session
        session.invalidate();
        //session.removeAttribute("USER_INFO");
        // 重定向到登录页面的跳转方法
        return "forward:/";
    }
}
